<template>
  <div class="admin-events">
    <h2>演出管理</h2>
    
    <!-- 搜索和添加按钮 -->
    <el-row :gutter="20" style="margin-bottom: 20px;">
      <el-col :span="8">
        <el-input
          v-model="searchQuery"
          placeholder="搜索演出名称"
          prefix-icon="el-icon-search"
          clearable
          @input="handleSearch"
        ></el-input>
      </el-col>
      <el-col :span="4">
        <el-button type="primary" @click="showAddDialog = true">添加演出</el-button>
      </el-col>
    </el-row>

    <!-- 演出列表 -->
    <el-table :data="filteredEvents" style="width: 100%">
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column prop="title" label="演出名称"></el-table-column>
      <el-table-column prop="venue" label="场馆" width="150"></el-table-column>
      <el-table-column prop="date" label="日期" width="120"></el-table-column>
      <el-table-column prop="price" label="价格" width="100">
        <template #default="scope">¥{{ scope.row.price }}</template>
      </el-table-column>
      <el-table-column prop="city" label="城市" width="100"></el-table-column>
      <el-table-column prop="category" label="分类" width="100"></el-table-column>
      <el-table-column label="操作" width="150">
        <template #default="scope">
          <el-button size="small" @click="editEvent(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteEvent(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="showAddDialog"
      :title="dialogTitle"
      width="600px"
      @close="resetForm"
    >
      <el-form
        :model="eventForm"
        :rules="eventRules"
        ref="eventFormRef"
        label-width="100px"
      >
        <el-form-item label="演出名称" prop="title">
          <el-input v-model="eventForm.title" placeholder="请输入演出名称"></el-input>
        </el-form-item>
        <el-form-item label="场馆" prop="venue">
          <el-input v-model="eventForm.venue" placeholder="请输入场馆名称"></el-input>
        </el-form-item>
        <el-form-item label="日期" prop="date">
          <el-date-picker
            v-model="eventForm.date"
            type="datetime"
            placeholder="选择日期时间"
            style="width: 100%;"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number v-model="eventForm.price" :min="0" :step="1" placeholder="请输入价格"></el-input-number>
        </el-form-item>
        <el-form-item label="城市" prop="city">
          <el-input v-model="eventForm.city" placeholder="请输入城市"></el-input>
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-input v-model="eventForm.category" placeholder="请输入分类"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="eventForm.description"
            type="textarea"
            rows="3"
            placeholder="请输入演出描述"
          ></el-input>
        </el-form-item>
        <el-form-item label="图片URL" prop="imageUrl">
          <el-input v-model="eventForm.imageUrl" placeholder="请输入图片URL"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddDialog = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import api from '../../api/index.js'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useAppStore } from '../../store'

export default {
  name: 'AdminEvents',
  setup() {
    const router = useRouter()
    const store = useAppStore()
    const events = ref([])
    const loading = ref(true)
    const searchQuery = ref('')
    const showAddDialog = ref(false)
    const eventForm = ref({
      id: null,
      title: '',
      venue: '',
      date: '',
      price: 0,
      city: '',
      category: '',
      description: '暂无描述',
      imageUrl: 'https://via.placeholder.com/300x200'
    })
    const eventFormRef = ref(null)
    const eventRules = {
      title: [{ required: true, message: '请输入演出名称', trigger: 'blur' }],
      venue: [{ required: true, message: '请输入场馆名称', trigger: 'blur' }],
      date: [{ required: true, message: '请选择日期', trigger: 'change' }],
      price: [{ required: true, message: '请输入价格', trigger: 'blur' }],
      city: [{ required: true, message: '请输入城市', trigger: 'blur' }],
      category: [{ required: true, message: '请输入分类', trigger: 'blur' }],
      description: [{ required: true, message: '请输入描述', trigger: 'blur' }],
      imageUrl: [{ required: true, message: '请输入图片URL', trigger: 'blur' }]
    }

    // 检查是否为管理员
    onMounted(() => {
      if (!store.isLoggedIn || !store.user?.is_admin) {
        ElMessage.error('需要管理员权限')
        router.push('/')
        return
      }
      fetchEvents()
    })

    // 获取所有演出
    const fetchEvents = async () => {
      try {
        loading.value = true
        const response = await api.get('/events')
        events.value = response
      } catch (error) {
        console.error('获取演出失败:', error)
        ElMessage.error('获取演出失败')
      } finally {
        loading.value = false
      }
    }

    // 根据搜索条件过滤演出
    const filteredEvents = computed(() => {
      if (!searchQuery.value.trim()) {
        return events.value
      }
      const query = searchQuery.value.toLowerCase().trim()
      return events.value.filter(event => 
        event.title.toLowerCase().includes(query)
      )
    })

    // 搜索处理
    const handleSearch = () => {
      // 搜索功能由computed属性自动处理
    }

    // 添加演出
    const addEvent = async () => {
      try {
        // 创建不包含id和imageUrl的对象
        const { id, imageUrl, ...formData } = eventForm.value
        // 添加后端需要的image_url字段
        formData.image_url = imageUrl || ''
        
        // 格式化日期为MySQL可接受的格式
        if (formData.date) {
          const date = new Date(formData.date)
          formData.date = date.toISOString().slice(0, 19).replace('T', ' ')
        }
        
        const response = await api.post('/events', formData)
        // 添加成功后重新获取数据
        fetchEvents()
        ElMessage.success('添加成功')
        showAddDialog.value = false
      } catch (error) {
        console.error('添加演出失败:', error)
        ElMessage.error(error.response?.data?.error || '添加演出失败')
      }
    }

    // 编辑演出
    const updateEvent = async () => {
      try {
        // 创建不包含id和imageUrl的对象
        const { id, imageUrl, ...formData } = eventForm.value
        // 添加后端需要的image_url字段
        formData.image_url = imageUrl || ''
        
        // 格式化日期为MySQL可接受的格式
        if (formData.date) {
          const date = new Date(formData.date)
          formData.date = date.toISOString().slice(0, 19).replace('T', ' ')
        }
        
        const response = await api.put(`/events/${id}`, formData)
        // 更新成功后重新获取数据
        fetchEvents()
        ElMessage.success('更新成功')
        showAddDialog.value = false
      } catch (error) {
        console.error('更新演出失败:', error)
        ElMessage.error(error.response?.data?.error || '更新演出失败')
      }
    }

    // 打开编辑对话框
    const editEvent = (event) => {
      eventForm.value = {
        id: event.id,
        title: event.title,
        venue: event.venue,
        date: event.date,
        price: event.price,
        city: event.city,
        category: event.category,
        description: event.description,
        imageUrl: event.imageUrl
      }
      showAddDialog.value = true
    }

    // 删除演出
    const deleteEvent = (id) => {
      ElMessageBox.confirm('确定要删除这个演出吗？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await api.delete(`/events/${id}`)
          // 删除成功后重新获取数据
          fetchEvents()
          ElMessage.success('删除成功')
        } catch (error) {
          console.error('删除演出失败:', error)
          ElMessage.error(error.response?.data?.error || '删除演出失败')
        }
      }).catch(() => {
        // 取消删除
      })
    }

    // 提交表单
    const submitForm = async () => {
      await eventFormRef.value.validate((valid) => {
        if (valid) {
          if (eventForm.value.id) {
            updateEvent()
          } else {
            addEvent()
          }
        }
      })
    }

    // 重置表单
    const resetForm = () => {
      eventForm.value = {
        id: null,
        title: '',
        venue: '',
        date: '',
        price: 0,
        city: '',
        category: '',
        description: '暂无描述',
        imageUrl: 'https://via.placeholder.com/300x200'
      }
      eventFormRef.value?.resetFields()
    }

    // 对话框标题
    const dialogTitle = computed(() => {
      return eventForm.value.id ? '编辑演出' : '添加演出'
    })

    return {
      events,
      loading,
      searchQuery,
      showAddDialog,
      eventForm,
      eventFormRef,
      eventRules,
      filteredEvents,
      dialogTitle,
      handleSearch,
      editEvent,
      deleteEvent,
      submitForm,
      resetForm
    }
  }
}
</script>

<style scoped>
.admin-events {
  padding: 20px;
}

h2 {
  margin-bottom: 20px;
  color: #333;
}
</style>